#include "drvSpi.h"
#include "stm32g0xx_hal.h"

SPI_HandleTypeDef handle;

int drvSpiInit(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    __HAL_RCC_SPI1_CLK_ENABLE();
    /*
    *SPI1 GPIO Configuration
    PA5     ------> SPI1_SCK
    PA7     ------> SPI1_MOSI
    */
    GPIO_InitStruct.Pin = GPIO_PIN_5|GPIO_PIN_6;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF5_SPI1;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    handle.Instance = SPI1;
    handle.Init.Mode = SPI_MODE_MASTER;//主模式
    handle.Init.Direction = SPI_DIRECTION_2LINES;//全双工
    handle.Init.DataSize = SPI_DATASIZE_8BIT;//数据位为8位
    handle.Init.CLKPolarity = SPI_POLARITY_LOW;//CPOL=0,low
    handle.Init.CLKPhase = SPI_PHASE_1EDGE;//CPHA为数据线的第一个变化沿
    handle.Init.NSS = SPI_NSS_SOFT;//软件控制NSS
    handle.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;//2分频，32M/2=16MHz
    handle.Init.FirstBit = SPI_FIRSTBIT_MSB;//最高位先发送
    handle.Init.TIMode = SPI_TIMODE_DISABLE;//TIMODE模式关闭
    handle.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;//CRC关闭
    HAL_SPI_Init(&handle);
    return 0;
}

int drvSpiDeInit(void)
{
    __HAL_RCC_SPI1_CLK_DISABLE();
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_5 | GPIO_PIN_6);
    HAL_SPI_DeInit(&handle);
    return 0;
}

int drvSpiRead(uint8_t *pdata, uint8_t len)
{
    return HAL_SPI_Transmit(&handle, pdata, len, 1000);
}

int drvSpiWrite(uint8_t *pdata, uint8_t len)
{
    return HAL_SPI_Receive(&handle, pdata, len, 1000);
}